package com.jiang.demo.depotstable.store;

import com.alibaba.druid.pool.DruidDataSource;
import com.jiang.demo.depotstable.dds.config.DDSConfig;
import com.jiang.demo.depotstable.dds.datasource.DDS;
import com.jiang.demo.depotstable.dds.datasource.DSContextHolder;
import com.jiang.demo.depotstable.domain.Store;
import com.jiang.demo.depotstable.domain.Type;
import com.jiang.demo.depotstable.mapper.StoreMapper;
import com.jiang.demo.depotstable.type.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author jiangzhe
 * @create 2021/5/11 16:00
 */
@Slf4j
@Configuration
@Service
public class StoreService {

    @Value("${spring.datasource.product.url}")
    private String productDBUrl;
    @Value("${spring.datasource.product.username}")
    private String productDBUser;
    @Value("${spring.datasource.product.password}")
    private String productDBPassword;
    @Value("${spring.datasource.product.driver-class-name}")
    private String productDBDriverName;

    @Autowired
    StoreMapper storeMapper;

    @Autowired
    TypeService typeService;

    public List<Store> getStoreInfos(){
        return storeMapper.getStoreInfos();
    }

    /**
     * 新建 store 时：
     * 1.动态添加对应数据源到 dsMap
     * 2.为新添加的数据源 新建表结构（根据已有的 type 表数据）
     */
    public void insertStore(Store store){
        DSContextHolder.setDBType("store-db");
        storeMapper.insertStore(store);
        setproductDDS(store);
        initProductTables(store.getName());
    }

    public void setproductDDS(Store store){
        DruidDataSource productDS = new DruidDataSource();
        productDS.setUrl(productDBUrl.replace("?port?", store.getPort()+""));
        productDS.setUsername(productDBUser);
        productDS.setPassword(productDBPassword);
        productDS.setDriverClassName(productDBDriverName);
        Map<Object, Object> dsMap = DDS.getInstance().getDataSourceMap();
        dsMap.put("product-db-" + store.getName(), productDS);
        DDS.getInstance().setTargetDataSources(dsMap);
        log.info(store.getName() + " product-db-" + store.getName() + " 数据源添加完毕");
    }

    public void initProductTables(String storeName){
        List<Type> typeList = typeService.getTypeInfos();
        DSContextHolder.setDBType("product-db-"+storeName);
        for (Type type: typeList) {
            typeService.createTable(TypeService.tableName_product, type.getId());
            typeService.createTable(TypeService.tableName_descript, type.getId());
            log.info("product-db-"+storeName + " 新建表："+ TypeService.tableName_product+type.getId());
        }
    }
}
